package cn.iocoder.yudao.module.erp.controller.app.purchase;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.out.ErpPurchaseOutSaveReqVO;
import cn.iocoder.yudao.module.erp.controller.app.purchase.vo.out.AppErpPurchaseOutPageReqVO;
import cn.iocoder.yudao.module.erp.controller.app.purchase.vo.out.AppErpPurchaseOutRespVO;
import cn.iocoder.yudao.module.erp.controller.app.purchase.vo.out.AppErpPurchaseOutSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseOutDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseOutItemsDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpSupplierDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.stock.ErpStockDO;
import cn.iocoder.yudao.module.erp.enums.ErpAuditStatus;
import cn.iocoder.yudao.module.erp.enums.ErpPurchaseOutStatus;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import cn.iocoder.yudao.module.erp.service.purchase.AppErpPurchaseOutService;
import cn.iocoder.yudao.module.erp.service.purchase.ErpSupplierService;
import cn.iocoder.yudao.module.erp.service.stock.ErpStockService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMultiMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;


@Tag(name = "应用端 - ERP 基础出库")
@RestController
@RequestMapping("/erp/purchase-out")
@Validated
public class AppErpPurchaseOutController {

    @Resource
    private AppErpPurchaseOutService purchaseOutService;
    @Resource
    private ErpStockService stockService;
    @Resource
    private ErpProductService productService;
    @Resource
    private ErpSupplierService supplierService;
    @Resource
    private AdminUserApi adminUserApi;



    @PostMapping("/update-status")
    @Operation(summary = "更新采购入库的状态")
    public CommonResult<Boolean> updatePurchaseInStatus(@RequestParam("id") Long id) {
        purchaseOutService.updatePurchaseOutStatus(id, ErpPurchaseOutStatus.OUT.getStatus());
        return success(true);
    }

    @PostMapping("/update")
    @Operation(summary = "更新ERP 基础出库")
    public CommonResult<Boolean> updatePurchaseOut(@Valid @RequestBody AppErpPurchaseOutSaveReqVO updateReqVO) {
        purchaseOutService.updatePurchaseOut(updateReqVO);
        return success(true);
    }



    @GetMapping("/get")
    @Operation(summary = "获得ERP 基础出库")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<AppErpPurchaseOutRespVO> getPurchaseOut(@RequestParam("id") Long id) {
        ErpPurchaseOutDO purchaseOut = purchaseOutService.getPurchaseOut(id);
        if (purchaseOut == null) {
            return success(null);
        }
        List<ErpPurchaseOutItemsDO> purchaseOutItemList = purchaseOutService.getPurchaseOutItemListByOutId(id);
        Map<Long, ErpProductRespVO> productMap = productService.getProductVOMap(
                convertSet(purchaseOutItemList, ErpPurchaseOutItemsDO::getProductId));
        return success(BeanUtils.toBean(purchaseOut, AppErpPurchaseOutRespVO.class, VO -> {
                    VO.setItems(BeanUtils.toBean(purchaseOutItemList, AppErpPurchaseOutRespVO.AppPurchaseOutItem.class, item -> {
                        ErpStockDO stock = stockService.getStock(item.getProductId(), item.getWarehouseId());
                        item.setStockCount(stock != null ? stock.getCount() : BigDecimal.ZERO);
                        MapUtils.findAndThen(productMap, item.getProductId(), product -> item.setProductName(product.getName())
                                .setProductBarCode(product.getBarCode()).setProductUnitName(product.getUnitName()));
                    }));
                    VO.setCreatorDepartment("测试部门2");
                }
        ));
    }

    @GetMapping("/page")
    @Operation(summary = "获得ERP 基础出库分页")
    public CommonResult<PageResult<AppErpPurchaseOutRespVO>> getPurchaseOutPage(@Valid AppErpPurchaseOutPageReqVO pageReqVO) {
        PageResult<ErpPurchaseOutDO> pageResult = purchaseOutService.getPurchaseOutPage(pageReqVO);
        return success(buildPageResult(pageResult));
    }



    private PageResult<AppErpPurchaseOutRespVO> buildPageResult(PageResult<ErpPurchaseOutDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        // 1.1 入库项
        List<ErpPurchaseOutItemsDO> purchaseOutItemList = purchaseOutService.getPurchaseOutItemListByOutIds(
                convertSet(pageResult.getList(), ErpPurchaseOutDO::getId));
        Map<Long, List<ErpPurchaseOutItemsDO>> purchaseOutItemMap = convertMultiMap(purchaseOutItemList, ErpPurchaseOutItemsDO::getOutId);
        // 1.2 产品信息
        Map<Long, ErpProductRespVO> productMap = productService.getProductVOMap(
                convertSet(purchaseOutItemList, ErpPurchaseOutItemsDO::getProductId));
        // 1.3 供应商信息
        Map<Long, ErpSupplierDO> supplierMap = supplierService.getSupplierMap(
                convertSet(pageResult.getList(), ErpPurchaseOutDO::getSupplierId));
        // 1.4 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), purchaseOut -> Long.parseLong(purchaseOut.getCreator())));
        // 2. 开始拼接
        return BeanUtils.toBean(pageResult, AppErpPurchaseOutRespVO.class, purchaseOut -> {
            purchaseOut.setItems(BeanUtils.toBean(purchaseOutItemMap.get(purchaseOut.getId()), AppErpPurchaseOutRespVO.AppPurchaseOutItem.class,
                    item -> MapUtils.findAndThen(productMap, item.getProductId(), product -> item.setProductName(product.getName())
                            .setProductBarCode(product.getBarCode()).setProductUnitName(product.getUnitName()))));
            purchaseOut.setProductNames(CollUtil.join(purchaseOut.getItems(), "，", AppErpPurchaseOutRespVO.AppPurchaseOutItem::getProductName));
            MapUtils.findAndThen(supplierMap, purchaseOut.getSupplierId(), supplier -> purchaseOut.setSupplierName(supplier.getName()));
            MapUtils.findAndThen(userMap, Long.parseLong(purchaseOut.getCreator()), user -> purchaseOut.setCreatorName(user.getNickname()));
            purchaseOut.setCreatorDepartment("测试部门");
        });
    }


}
